<?php
/**
 * --------------------------------------------------------------------
 * MCore精简框架
 * 作者：阿枫，QQ：52037872，Email：support@mdeve.com
 * --------------------------------------------------------------------
 *
 * SVN revision information:
 * @version $Revision: 1 $:
 * @author  $Author: zy $:
 * @date      $Date: 2017-03-10 21:12:21 +0800 (星期五, 10 三月 2017) $:
 */

require_once dirname(__FILE__) . "/abstract_cache.php";

class CacheRedis extends _cache_interface {
    private $_prefix = '';
    public $_enable;
    protected $_redis;

    function __construct(){
        global $config;
        $this->_prefix = $config['memory']['prefix'];
        $this->_enable = in_array("redis", get_loaded_extensions());
        if($this->_enable){
            $this->_redis = new Redis();
            $this->_redis->connect($config['memory']['redis_server'], $config['memory']['redis_port']);
            $this->_redis->auth($config['memory']['redis_passwd']);
            $this->_redis->select($config['memory']['redis_database']); // switch to DB
        }
    }

    function __destruct(){
        if($this->_enable) $this->_redis = null;
    }



    /**
     * 返回是否支持缓存，在使用前先判断，否则不支持的话强行使用会出错。
     * @return boolean
     */
    function is_support(){
        return $this->_enable;
    }

    /**
     * 判断缓存变量是否存在
     * @param string $key
     * @return bool
     */
    public function exists($key){
        if(!$this->_enable) $this->_err();

        return $this->_redis->exists($this->_storageKey($key));
    }

    /**
     * 读缓存变量
     *
     * @param string $key
     * @return mixed
     */
    public function fetch($key) {
        if(!$this->_enable) $this->_err();
        $data = $this->_redis->get ( $this->_storageKey ( $key ) );
        $s = @unserialize($data);
        return false===$s ? $data : $s;
    }

    /**
     * 缓存变量
     *
     * @param string $key
     * @param string $value
     * @return bool
     */
    public function store($key, $val, $time=0) {
        if(!$this->_enable) $this->_err();
        if(is_array($val)) $val = serialize($val);
        if($this->_exist_redis()) {
            if ($time) {
                return $this->_redis->setex($this->_storageKey($key), $time, $val);
            } else {
                return $this->_redis->set($this->_storageKey($key), $val);
            }
        }
        return false;
    }

    /**
     * 删除缓存变量
     *
     * @param string $key
     * @return bool
     */
    public function delete($key) {
        if(!$this->_enable) $this->_err();
        return $this->_redis->delete ( $this->_storageKey ( $key ) );

    }

    /**
     * 清(删)除所有缓存
     *
     * @param string $cache_type 缓存类型，默认为 user ，否则系统缓存(缓存文件)将被清除
     * @return bool
     */
    public function clear($cache_type="user") {

        if(!$this->_enable) $this->_err();
        if($this->_exist_redis()) {
            $this->_redis->flushDB();
        }

    }


    /**
     * 用通配符来获取 key 列表
     * @param $key
     * @return mixed
     *
     */
    public function keys($key) {

        $keys = $this->_redis->keys( $this->_storageKey ( $key ) );
        natsort($keys);
        $array = array();
        foreach($keys as $k) {
            $array[] = str_replace($this->_prefix, "", $k);
        }
        return $array;

    }

    public function server_info(){
        return $this->_redis->info();
    }

    private function _storageKey($key) {
        return $this->_prefix . $key;
    }

    private function _err(){
        halt ( 'Redis extension didn\'t installed' );
    }

    private function _exist_redis(){
        return $this->_redis !== null;
    }


}